import { useFrame } from "@react-three/fiber";
import { useRef, useEffect } from "react";
import * as THREE from "three";
import { MathUtils } from "three";
export function Sora({ count = 10000, temp = new THREE.Object3D(), data }) {
  const ref = useRef<THREE.InstancedMesh>(null);
  useFrame(({ clock }) => {
    if (ref.current) {
      ref.current.rotation.y = clock.elapsedTime * Math.PI * 0.001;
      if (!data.current.start)
        ref.current.rotation.x = clock.elapsedTime * 0.25;
    }
  });
  useEffect(() => {
    // Set positions
    for (let i = 0; i < count; i++) {
      let z = MathUtils.randFloatSpread(1000000);
      if (Math.abs(z) < 5000) {
        z += 5000 * (Math.abs(z) / z);
      }
      temp.position.set(
        MathUtils.randFloatSpread(1000000),
        MathUtils.randFloatSpread(1000000),
        z
      );
      temp.updateMatrix();
      ref.current!.setMatrixAt(i, temp.matrix);
    }
    // Update the instance
    ref.current!.instanceMatrix.needsUpdate = true;
  }, [count, temp]);
  return (
    <instancedMesh ref={ref} args={[undefined, undefined, count]}>
      <sphereBufferGeometry args={[MathUtils.randFloat(100, 300)]} />
      <meshBasicMaterial />
    </instancedMesh>
  );
}
